package com.fly.ribbon.config

import feign.RequestInterceptor
import org.springframework.context.annotation.Bean
import org.springframework.web.context.request.RequestContextHolder
import org.springframework.web.context.request.ServletRequestAttributes
import javax.annotation.PostConstruct

/**
 * @author  fly
 * @date  2021/5/18 16:21
 * @version 1.0
 */

/**
 * 用户id信息头
 */
const val USER_ID_HEADER = "x-userid-header"

/**
 *用户信息头
 */
const val USER_HEADER = "x-user-header"

/**
 * 角色信息头
 */
const val ROLE_HEADER = "x-role-header"

/**
 * 负载均衡策略-版本号 信息头
 */
const val Z_L_T_VERSION = "z-l-t-version"

open class FeignHttpInterceptorConfig {

    private val requestHeaders = arrayListOf<String>()

    @PostConstruct
    fun initialize() {
        requestHeaders.add(USER_ID_HEADER)
        requestHeaders.add(USER_HEADER)
        requestHeaders.add(ROLE_HEADER)
        requestHeaders.add(Z_L_T_VERSION)
    }

    @Bean
    fun httpFeignInterceptor(): RequestInterceptor = RequestInterceptor {

        val servletRequestAttributes = RequestContextHolder.getRequestAttributes() as ServletRequestAttributes?
        servletRequestAttributes?.run {
            servletRequestAttributes.request.headerNames?.run {

                while (hasMoreElements()) {
                    val headerName = nextElement()
                    if (requestHeaders.contains(headerName))
                        it.header(headerName, servletRequestAttributes.request.getHeader(headerName))
                }
            }
        }
    }
}